package com.kkui.liuxin.controller;

import com.kkui.liuxin.pojo.User;
import com.kkui.liuxin.service.UserService;
import com.kkui.liuxin.shiro_jwt.JwtUtil;
import com.kkui.liuxin.shiro_jwt.jwtToken;
import com.kkui.liuxin.shiro_jwt.saltUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.ExpiredCredentialsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

/**
 * @author kkui
 * descriptor:This user login web controller
 */
@Slf4j
@Controller
@RequestMapping("/user")
public class Login {
    @Resource
    saltUtil saltutil;
    @Resource
    UserService service;

    @PostMapping("/login")
    @ResponseBody
    public String login(@RequestBody User user, HttpServletResponse response){

        String Name = user.getUsername();
        String PassWord = user.getPwd();

        if (service.getUserInfoByName(Name)==null){
            return "用户名不存在";
        }

        Md5Hash md5Hash = new Md5Hash(PassWord, service.getSaltByName(Name).getSalt(), 1024);

        //生成token字符串  toHex转换成16进制，32为字符
        String token = JwtUtil.getJwtToken(Name, md5Hash.toHex());
        jwtToken jwtToken = new jwtToken(token);


        //拿到Subject对象
        Subject subject = SecurityUtils.getSubject();

        //进行认证
        try {
            subject.login(jwtToken);
            //想让浏览器能访问到其他的 响应头的话 需要在服务器上设置 Access-Control-Expose-Headers
            response.setHeader("Access-Control-Expose-Headers", "*");
            response.setHeader("Authorization",token);
            return "登陆成功";
        } catch (UnknownAccountException e){
            e.printStackTrace();
            return "无效用户，用户不存在";
        } catch (IncorrectCredentialsException e){
            e.printStackTrace();
            return "输入密码错误";
        } catch (ExpiredCredentialsException e){
            e.printStackTrace();
            return "token过期，请重新登录";
        }

    }
}
